<?php
/**
 * Created by IntelliJ IDEA.
 * User: jimmyhsu
 * Date: 2017/4/2
 * Time: 18:18
 */
include('../Teacher/db/conn.php');
include('facepp.php');
include('bdaip.php');
$username = $_POST['username'];
$password = $_POST['password'];
$token = $_POST['token'];
$sql = "select * from userinfo where name='$username' and password='" . md5($password) . "'";
//echo $sql;
$query = mysqli_query($cn, $sql);
if (mysqli_num_rows($query) > 0) {
    $arr = mysqli_fetch_array($query);
    $id = $arr['id'];
    $preToken = $arr['token'];
    $facepp = new facepp();
    $bdaip = new bdaip();
    if ($preToken != '') {
        $sql = "SELECT faceset_token FROM course";
        $query = mysqli_query($cn, $sql);
        while ($line = mysqli_fetch_assoc($query)) {
            $result = $facepp->remove_face_from_faceset($line['faceset_token'], $preToken);
            sleep(1);
        }
        $facepp->remove_face_from_faceset("540f959db75ebaca76478ba8015a6a75", $preToken);
        sleep(1);
    }

    $json = $facepp->add_face(facepp::faceset_all, $token);
    if ($json['face_added'] == 1) {
        $sql = "update userinfo set token='$token' where name='$username'";
        if (mysqli_query($cn, $sql)) {
            $sql = "select course_id, faceset_token from course natural join takes where id=$id and faceset_token != ''";
            $query = mysqli_query($cn, $sql);
            while ($row = mysqli_fetch_assoc($query)) {
                $facepp->add_face($row['faceset_token'], $token);
                $bd_gid = str_replace('.', '_', $row['course_id']);
                $bdaip->addToGroup($username, $bd_gid);
                sleep(1);
            }
            echo "success";
        } else {
            echo "db";
        }
    } else {
        echo "facepp: " . print_r($json);
    }
} else {
    echo "invalid user";
}
